package com.bantang.utils;

import cn.hutool.core.date.StopWatch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 编译代码工具类
 */
public class CompileCodeUtil {

    public static final Long MAX_TIME = 5000 * 1L;

    public static ExecResult compileCode(String codeCmd) {

        System.out.println("指令");
        System.out.println(codeCmd);

        //开启记时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        //返回参数对象
        ExecResult compileResult = new ExecResult();

        Process process;

        try {
            process = Runtime.getRuntime().exec(codeCmd);

            //超时限制默认限制 1秒
            limitTime(process);

            int statCode = process.waitFor();//这个是线程阻塞的 不会报错
            // int statCode = process.exitValue(); 这个如果不关闭的话 会报错
            System.out.println("状态"+statCode);
            if (statCode == 0) {

                String result = getOutputResult(process, false);

                compileResult.setMessage("success");
                compileResult.setOutput(result);
            } else {

                String result = getOutputResult(process, true);
                compileResult.setMessage(result);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
        }
        stopWatch.stop();
        compileResult.setTime(stopWatch.getLastTaskTimeMillis());

        return compileResult;
    }


    private static void limitTime(Process process) {
        System.out.println("limitTime");
        new Thread(
                () -> {
                    try {
                        Thread.sleep(MAX_TIME);
                        process.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
        ).start();
    }

    private static String getOutputResult(Process process, boolean isSuccess) throws IOException {
        BufferedReader bufferedReader;
        //获取输出结果
        if (!isSuccess) {
            System.out.println("成功 打印出入用例");
            //成功 打印出入用例
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        } else {
            System.out.println("失败 打印错误提示");
            //失败 打印错误提示
            bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        }

        StringBuilder compileInputBuilder = new StringBuilder();
        String readLineText;

        while ((readLineText = bufferedReader.readLine()) != null) {
            compileInputBuilder.append(readLineText);
        }
        return compileInputBuilder.toString();
    }
}
